package com.example.JcGQS.ElasticsearchApiExample;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.JcGQS.dao.GoodsDao;
import com.example.JcGQS.pojo.entity.Goods;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class test {

    public static void main(String[] args) {
//        Goods goods1 = new Goods(1,"WL866797983",4,"四通接头","西门本 2.7","FX3U-32MT","瓶");
//
//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("goods_id",goods1.getGoodsId());
//        jsonObject.put("goods_number", goods1.getGoodsNumber());
//        jsonObject.put("category_id",goods1.getCategoryId());
//        jsonObject.put("good_name", goods1.getGoodsName());
//        jsonObject.put("goods_specification", goods1.getGoodsSpecification());
//        jsonObject.put("goods_model", goods1.getGoodsModel());
//        jsonObject.put("goods_unit",goods1.getGoodsUnit());
//        System.out.println(jsonObject);
//        System.out.println(jsonObject.toString());
//
        // 设置 Elasticsearch 节点的地址和端口
        String elasticsearchHost = "localhost";
        int elasticsearchPort = 9200;

        // 设置索引名称
        String indexName = "testgoods";

        try {
            // 1. 创建索引
            //createIndex(elasticsearchHost, elasticsearchPort, indexName);

            // 2. 插入数据
            //insertData(elasticsearchHost, elasticsearchPort, indexName);

            // 3. 删除数据
            //deleteData(elasticsearchHost, elasticsearchPort, indexName, 1);

            // 4. 全局搜索
            globalSearch(elasticsearchHost, elasticsearchPort, indexName, "西");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建索引
     * @param host 地址
     * @param port 端口
     * @param indexName 索引名
     * @throws IOException
     */
    private static void createIndex(String host, int port, String indexName) throws IOException {
        URL url = new URL("http://" + host + ":" + port + "/" + indexName);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("PUT");

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
            String line;
            StringBuilder response = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }

          //  System.out.println("Index created successfully. Response: " + response.toString());
        } finally {
            connection.disconnect();
        }
    }


    /**
     * 新增ES数据
     * @param host 地址
     * @param port 端口
     * @param indexName 索引
     * @throws IOException
     */
    private static void insertData(String host, int port, String indexName) throws IOException {
        URL url = new URL("http://" + host + ":" + port + "/" + indexName + "/_doc/"+4);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);

        Goods goods1 = new Goods(1,"WL8667983",4,"接头","西","FT","瓶","12");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("goods_id",goods1.getGoodsId());
        jsonObject.put("goods_number", goods1.getGoodsNumber());
        jsonObject.put("category_id",goods1.getCategoryId());
        jsonObject.put("good_name", goods1.getGoodsName());
        jsonObject.put("goods_specification", goods1.getGoodsSpecification());
        jsonObject.put("goods_model", goods1.getGoodsModel());
        jsonObject.put("goods_unit",goods1.getGoodsUnit());
//        System.out.println(jsonObject);
//        System.out.println(jsonObject.toString());

        String data = jsonObject.toString() ;
        try (OutputStream os = connection.getOutputStream()) {
            os.write(data.getBytes());
        }

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
            String line;
            StringBuilder response = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }

//            System.out.println("Document created successfully. Response: " + response.toString());
        } finally {
            connection.disconnect();
        }
    }

    /**
     * 删除ES数据
     * @param host 地址
     * @param port 端口
     * @param indexName 索引
     * @param documentId 标志id
     * @throws IOException
     */
    private static void deleteData(String host, int port, String indexName, Integer documentId) throws IOException {
        URL url = new URL("http://" + host + ":" + port + "/" + indexName + "/_doc/" + documentId);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("DELETE");

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
            String line;
            StringBuilder response = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
//            System.out.println("Document deleted successfully. Response: " + response.toString());
        } finally {
            connection.disconnect();
        }
    }

    /**
     * 全局搜索
     * @param host  地址
     * @param port 端口
     * @param indexName 索引
     * @param searchKeyword 搜索内容
     * @throws IOException
     */
    private static void globalSearch(String host, int port, String indexName, String searchKeyword) throws IOException {
        // 构建查询字符串
        String queryString = "{\"query\": {\"query_string\": {\"query\": \"*"+searchKeyword+"*\"}}}";

        URL url = new URL("http://" + host + ":" + port + "/" + indexName + "/_search");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);

        try (OutputStream os = connection.getOutputStream()) {
            os.write(queryString.getBytes());
        }

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
            String line;
            StringBuilder response = new StringBuilder();
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
//            System.out.println("Search results: " + response.toString());
            JSONObject jsonObject = JSON.parseObject(response.toString());
            JSONObject hits = jsonObject.getJSONObject("hits");
            List<Goods> goodsList = new ArrayList<>();
            JSONArray hitsArray = hits.getJSONArray("hits");
            for (int i = 0; i < hitsArray.size(); i++) {
                JSONObject firstHit = hitsArray.getJSONObject(i);

                JSONObject source = firstHit.getJSONObject("_source");
                Goods goods = new Goods(
                        source.getInteger("goods_id"),
                        source.getString("goods_number"),
                        source.getInteger("category_id"),
                        source.getString("good_name"),
                        source.getString("goods_specification"),
                        source.getString("goods_model"),
                        source.getString("goods_number"),
                        source.getString("brand")
                );
//                System.out.println(goods);
                goodsList.add(goods);
//                System.out.println(goodsList);
            }
        } finally {
            connection.disconnect();
        }
    }
        }

